# 列表推导式

# 计算0-9的平方列表
varl = []
for i in range(0, 10):
    varl.append(i**2)
print(varl)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 使用map函数和list函数完成
varl = list(map(lambda x: x**2, range(10)))
print(varl)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 使用列表推导式
# 1，基本的列表推导式使用方法
# 变量 = [变量的处理结果 for 变量 in 容器类型数据]
varl = [i**2 for i in range(10)]
print(varl)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# '1234' ===> [2,4,6,8]
varl = [int(i)*2 for i in '1234']
print(varl)
# [2, 4, 6, 8]

# 2，带有判断条件的列表推导式
# 变量 = [变量的处理结果 for 变量 in 容器类型数据 条件表达式]

# 0-9 的偶数
varl = [i for i in range(10) if i % 2 == 0]
print(varl)

# 3，带有条件判断的多循环推导式
# 把两个列表中的元素两两组合，要求组合的元素不饿能重复

newlist = []
for x in [1, 2, 3]:
    for y in [3, 1, 4]:
        if x != y:
            newlist.append((x, y))
print(newlist)
# [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

varl1 = [1, 2, 3]
varl2 = [3, 1, 4]
varl = [(x, y) for x in varl1 for y in varl2 if x != y]
print(varl)
# [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

# 嵌套循环推导式
# 将一个二维数组的行和列互换
dvarl = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
]
resdvarl = [[item[i] for item in dvarl] for i in range(len(dvarl[0]))]
print(resdvarl)
# [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

# 练习：使用列表推导式实现九九乘法表
res = [f'{x}*{y}={x*y}' for x in range(1, 10) for y in range(1, 10) if x<=y]
print(res)
'''
[
'1*1=1', '1*2=2', '1*3=3', '1*4=4', '1*5=5', '1*6=6', '1*7=7', '1*8=8', '1*9=9', 
'2*2=4', '2*3=6', '2*4=8', '2*5=10', '2*6=12', '2*7=14', '2*8=16', '2*9=18', 
'3*3=9', '3*4=12', '3*5=15', '3*6=18', '3*7=21', '3*8=24', '3*9=27', 
'4*4=16', '4*5=20', '4*6=24', '4*7=28', '4*8=32', '4*9=36', 
'5*5=25', '5*6=30', '5*7=35', '5*8=40', '5*9=45', 
'6*6=36', '6*7=42', '6*8=48', '6*9=54', 
'7*7=49', '7*8=56', '7*9=63', 
'8*8=64', '8*9=72', 
'9*9=81'
]
'''


